package com.kfm.wiki.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kfm.wiki.entity.User;
import com.kfm.wiki.entity.User;
import com.kfm.wiki.ex.BusinessException;
import com.kfm.wiki.ex.BusinessExceptionCode;
import com.kfm.wiki.service.UserService;
import com.kfm.wiki.mapper.UserMapper;
import com.kfm.wiki.util.PageReq;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
* @author 10854
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2022-10-21 14:37:38
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public Page<User> page(User user, PageReq page) {
        if (ObjectUtil.isEmpty(user)){
            return null;
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(user.getName())){
            wrapper.like("name", user.getName());
        }
        PageHelper.startPage(page.getPage(), page.getSize());
        Page<User> users = (Page<User>) getBaseMapper().selectList(wrapper);
        return users;
    }

    @Override
    public boolean save(User user) {
        if (ObjectUtil.isEmpty(user.getId())){
            if (hasUserName(user.getUsername())) {
                throw new BusinessException(BusinessExceptionCode.USERNAME_EXIT);
            }
            user.setId(IdUtil.getSnowflakeNextId());
            return getBaseMapper().insert(user) == 1;
        } else {
            user.setUsername(null);
            user.setPassword(null);
            return getBaseMapper().updateById(user) == 1;
        }
    }

    @Override
    public void resetPassword(User user) {
        user.setName(null);
        user.setUsername(null);
        getBaseMapper().updateById(user);
    }

    @Override
    public User login(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "username");
        wrapper.eq("username", user.getUsername());
        wrapper.eq("password", user.getPassword());
        User user1 = getBaseMapper().selectOne(wrapper);

        if (ObjectUtil.isNotEmpty(user1)){
            // 登录成功
            return user1;
        } else {
            throw new BusinessException(BusinessExceptionCode.USERNAME_OR_PASSWORD_ERROR);
        }
    }

    private boolean hasUserName(String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return ObjectUtil.isNotEmpty(getBaseMapper().selectList(wrapper));
    }

}




